#include <stdafx.h>

int logonUser(CString username, CString password, CString domain)
{
	HANDLE tokenHandle = NULL;
	int errorCode = 0;
	int isOk = LogonUser(username, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &tokenHandle);
	
	if (! isOk)
	{
		errorCode = GetLastError();

		return errorCode;
	}

	HANDLE dupToken = NULL;

	isOk = DuplicateToken(tokenHandle,SecurityImpersonation, &dupToken);

	if (!isOk)
	{
		errorCode = GetLastError();
		CloseHandle(tokenHandle);
		return errorCode;
	}
	else
	{
		// duplicate ok
		if (ImpersonateLoggedOnUser(dupToken) == FALSE)
		{
			errorCode = GetLastError();
			return errorCode;
		}
	}

	if (tokenHandle != NULL)
	{
		CloseHandle(tokenHandle);
	}

	if (dupToken != NULL)
	{
		CloseHandle(dupToken);
	}

	return errorCode;
}
